<template>
  <div class="storageManage" id="storageManage">
    <!-- 消息模板的tab切换 -->
    <baseTabs @changeTabs="changeTopTabs" :activeKey="reqTelListOption.tplType" :tabsList="tabsList" v-slot="{ item }">
      <div class="storageManage_button">
        <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="addRecord(item)">
          <template #icon>
            <span class="iconfont icon-Add iconadd"></span>
          </template>
          新建
        </a-button>

        <div class="header-right">
          <div v-show="reqTelListOption.tplType == 1" class="select-OSS">
            <div class="title">存储类型：</div>
            <a-select v-model:value="typeValue" :options="typeOptions" @select="onSelectType"></a-select>
          </div>
          <div class="searchContent">
            <a-input v-model:value="name" :placeholder="item.placeholder" style="width: 192px">
              <template #suffix>
                <i class="iconfont icon-search" @click="onSearch(item.key)"></i>
              </template>
            </a-input>
          </div>
        </div>
      </div>
    </baseTabs>
    <!-- 表格展示部分 -->
    <treeTable :columns="storageManageColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">编辑</a>
          <a-popconfirm :disabled="!btnPerm.includes('deleteAble')" placement="topRight" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                是否删除此{{ tabsList[reqTelListOption.tplType - 1].label }}
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button></template>
    </treeTable>
  </div>
  <!-- 索引号管理新建和编辑的对话框组件 -->
  <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
    @handleOk="buttonMessage" @handleCancle="isVisible = false" class="tagword_modal">
    <template v-slot:body>
      <base-form :isAutoUpload="true" :formState="formState" ref="storageManageForm" v-if="isVisible">
      </base-form>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, computed, watch, reactive, onMounted, nextTick, createVNode } from "vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import baseModal from "@/components/modal/baseModal.vue";
import baseTabs from "@/components/tabs/baseTabs.vue";
import treeTable from "@/components/table/baseTable.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import request from "@/api/index";
import {
  scrollType,
  dataSourceType,
  detailDataType,
  configDataType,
  modeProp,
} from "@/type.d";
import { encrypt3DES } from "@/utils/cryptojs";
import { storageManageForm1, storageManageForm2 } from "./formCofig";
import baseForm from "@/components/form/baseForm.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message, SelectProps } from "ant-design-vue";
import { cloneDeep } from "lodash";
import {routerPerm} from '@/utils/common';

//data
const btnPerm = ref<any[]>([]);
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
let name = ref<string>("");
const storageManageColumns = ref<any[]>(columns.storageManageColumns1);
const upOrgOptions = ref([]);
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const reqTelListOption = ref({
  //控制分页数据请求的变量集合
  tplType: 1,
});
let resOssData: dataSourceType = reactive({
  //头部筛选请求参数格式
  ossName: "",
  ossType: "",
  pageNumber: 0,
  pageSize: 10,
  pageSort: "",
});
let resFtpData: dataSourceType = reactive({
  //头部筛选请求参数格式
  ftpName: "",
  pageNumber: 0,
  pageSize: 10,
  pageSort: "",
});
const typeValue = ref<string>("全部");
const typeOptions = ref<any["options"]>([
  { name: "全部", id: null, value: "全部" },
  { name: "腾讯云", id: 1, value: "腾讯云" },
  { name: "阿里云", id: 2, value: "阿里云" },
  { name: "七牛云", id: 3, value: "七牛云" },
  { name: "MinIO", id: 4, value: "MinIO" },
  { name: "Aws", id: 5, value: "Aws" },
]);
//头部切换选项
const tabsList = [
  {
    tabName: "OSS云储存",
    label: "OSS云储存",
    placeholder: "搜索OSS名称",
    add: "新建OSS云储存",
    key: 1,
  },
  {
    tabName: "FTP",
    label: "FTP",
    placeholder: "搜索FTP名称",
    add: "新建FTP",
    key: 2,
  },
];
const formState = ref<dataSourceType[]>(cloneDeep(storageManageForm1));
let storageManageNewValue: dataSourceType = ref({});

const showCheckDelete = true; // 是否需要分页器中的自定义
const storageManageForm = ref<any>();
const editId = ref<any>();
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
//编辑项
let scroll: scrollType = reactive({ y: "", isFixed: false });
//索引号管理集中数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });

// const dataList = ref(dataSource.value.slice(0, 10))
const modAlProps: modeProp = reactive({
  width: "M",
  title: "",
});
//选择人员密级
const onSelectType = (val: string, option: any) => {
  resOssData.ossType = option.id;
  fetchOssPage();
};
const deleteArr = ref<(string | number)[]>([]);
const isVisible = ref(false); //控制是否展示编辑对话框
let rowSelection = ref<(string | number)[]>([]);
const tagBaseTables = ref<any>(null); // basetable的ref

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  fetchOssPage();
});

//methods
//改变头部tab切换
const changeTopTabs = (activeKey: number) => {
  reqTelListOption.value.tplType = activeKey;
  const indexNumber = `storageManageColumns${activeKey}`;
  const storageManageForm = activeKey == 1 ? storageManageForm1 : storageManageForm2;
  const columnsAll: any = columns;
  storageManageColumns.value = columnsAll[indexNumber];
  formState.value = cloneDeep(storageManageForm);
  name.value = "";
  if (activeKey == 1) {
    fetchOssPage();
  } else {
    fetchFtpPage();
  }
};

const addRecord = async (item: dataSourceType) => {
  //添加内容类型数据
  isVisible.value = true;
  modAlProps.title = item.add;
  //storageManageNewValue.value = { ...{ ossType: 1 } };
  storageManageNewValue.value = {};
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if(!btnPerm.value.includes('editAble')) return
  //编辑内容类型数据
  const data = await request[
    reqTelListOption.value.tplType == 1 ? "fetchOssDetail" : "fetchFtpDetail"
  ]({ id: item.id });
  data.port ? (data.port = data.port + "") : "";
  storageManageNewValue.value = { ...data };
  editId.value = item.id;
  modAlProps.title = `编辑${tabsList[reqTelListOption.value.tplType - 1].label}`;
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  isVisible.value = true;
};

const confirmDelete = async (item: any) => {
  // 删除单个
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除组织
  await request[
    reqTelListOption.value.tplType === 1 ? "fetchOssDelete" : "fetchFtpDelete"
  ]({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      if (reqTelListOption.value.tplType === 1) {
        fetchOssPage();
      } else {
        fetchFtpPage();
      }
    }
  });
};

const deleteSelectedAll = async () => {
  //删除已选所有内容类型
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: `您确定删除选中的${tabsList[reqTelListOption.value.tplType - 1].label}`,
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

const onSearch = async (key: number) => {
  //搜索获取数据参数配置
  if (reqTelListOption.value.tplType === 1) {
    fetchOssPage();
  } else {
    fetchFtpPage();
  }
};

//OSS列表分页
const fetchOssPage = async (datas: dataSourceType = {}) => {
  console.log(resOssData, "resOssData");
  const postData = {
    ossName: name.value,
    ossType: resOssData.ossType,
    pageNumber: resOssData.pageNumber,
    pageSize: resOssData.pageSize,
    pageSort: resOssData.pageSort,
  };
  const data = await request.fetchOssPage(postData);
  data.records.length &&
    data.records.forEach((item: dataSourceType) => {
      item.ossType = typeOptions.value[item.ossType].name;
    });
  configData.total = data.total;
  configData.records = data.records;
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "storageManage", 36);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};

//FTP列表分页
const fetchFtpPage = async (datas: dataSourceType = {}) => {
  const postData = {
    ftpName: name.value,
    pageNumber: resFtpData.pageNumber,
    pageSize: resFtpData.pageSize,
    pageSort: resFtpData.pageSort,
  };
  const data = await request.fetchFtpPage(postData);
  configData.total = data.total;
  configData.records = data.records;
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "storageManage", 36);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};

//FTP列表分页
const fetchIndexNumberPageList = async (datas: dataSourceType = {}) => {
  const postData = {
    type: reqTelListOption.value.tplType == 3 ? 4 : 5,
    name: name.value,
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
  };
  const data = await request.fetchIndexNumberPageList(postData);
  configData.total = data.total;
  configData.records = data.records;
  nextTick(() => {
    let obj = getTableScroll(74, "storageManage", 36);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  resOssData.pageNumber = data.pageCurrent;
  resOssData.pageSize = data.pageSize;
  resFtpData.pageNumber = data.pageCurrent;
  resFtpData.pageSize = data.pageSize;
  if (reqTelListOption.value.tplType === 1) {
    // resOssData.pageNumber = data.pageCurrent;
    // resOssData.pageSize = data.pageSize;
    fetchOssPage();
  } else {
    // resFtpData.pageNumber = data.pageCurrent;
    // resFtpData.pageSize = data.pageSize;
    fetchFtpPage();
  }
};

//对话框的确定保存
const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑组织调取接口
  //保存

  storageManageForm.value.baseForm
    .validate()
    .then(() => {
      if (reqTelListOption.value.tplType == 1) {
        let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
        const params = setNewValue();
        request[type === "Edit" ? "fetchOssUpdate" : "fetchOssAdd"](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchOssPage();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
        const params = setNewValue();

        request[type === "Edit" ? "fetchFtpUpdate" : "fetchFtpAdd"](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchFtpPage();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }
      storageManageForm.value.baseForm.resetFields();
      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => { });
};

//computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});

const setNewValue = () => {
  formState.value.forEach((item: dataSourceType) => {
    item.children.forEach((data: dataSourceType) => {
      if (data.hasOwnProperty("param")) {
        if (data.param === "ossType") {
          storageManageNewValue.value[data.param] = Number(data.value);
        } else {
          if (data.param === "password") {
            storageManageNewValue.value[data.param] =
              data.value === "" ? null : encrypt3DES(data.value);
          } else {
            storageManageNewValue.value[data.param] =
              data.value === "" ? null : data.value;
          }
        }
      }
    });
  });

  return storageManageNewValue.value;
};

//watch
watch(
  () => storageManageNewValue.value,
  (newVal: any, oldVal) => {
    if (!Object.keys(newVal).length) {
      formState.value =
        reqTelListOption.value.tplType == 1
          ? cloneDeep(storageManageForm1)
          : cloneDeep(storageManageForm2);
      formState.value =
        reqTelListOption.value.tplType == 1
          ? cloneDeep(storageManageForm1)
          : cloneDeep(storageManageForm2);
      formState.value.forEach((item) => {
        item.children.forEach((data: dataSourceType) => {
          if (newVal.hasOwnProperty(data.param)) {
            data.value = newVal[data.param] == "";
          }
        });
      });
      return;
    }
    if (!newVal) {
      formState.value =
        reqTelListOption.value.tplType == 1
          ? cloneDeep(storageManageForm1)
          : cloneDeep(storageManageForm2);
      return;
    }

    if (JSON.stringify(newVal)) {
      formState.value.forEach((item) => {
        item.children.forEach((data: dataSourceType) => {
          if (newVal.hasOwnProperty(data.param)) {
            data.value = newVal[data.param] != null ? newVal[data.param] : "";
            if (data.param === "ossType") {
              data.value = typeOptions.value[data.value].id;
            } else if (data.param === "ftpName" || data.param === "ossName") {
              data.rule.id = editId.value;
            }
          }
        });
      });
    }
  }
);
</script>

<style lang="less" scoped>
.storageManage {
  // display: flex;
  // flex-direction: column;
  background-color: #fff;
  padding: 16px;
  height: calc(100% - 72px);
  overflow: hidden;

  .storageManage_button {
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .header-right {
      margin-left: auto;
      margin-right: 0px;
      display: flex;
      flex-direction: row;
      align-items: center;

      .select-OSS {
        display: flex;
        flex-direction: row;
        align-items: center;
      }

      .searchContent {
        margin-left: 8px;

        .icon-search {
          font-size: 20px;
          color: rgba(0, 0, 0, 0.45);
          position: absolute;
          right: 12px;
          top: 0px;
        }
      }
    }
  }

  .eidtRecords {
    margin-right: 16px;
  }

  ::v-deep(.ant-select) {
    width: 124px !important;
  }

  ::v-deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }
}

.edit-body {
  display: flex;
  flex-direction: column;

  .telEdit {
    display: flex;
    flex-direction: column;
  }

  .telName {
    width: 72px;
    text-align: right;
  }

  .telNameInput {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .telSign {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;
  }

  .telDecTextarea {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .msgModel {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }

  .editTabsContent {
    display: flex;
    flex-direction: column;

    .editStatus {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }
}

::v-deep(.year .ant-input-affix-wrapper) {
  width: 540px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 480px;
}

::v-deep(.ant-form-item-label) {
  width: 78px !important;
  max-height: 98px;
  text-align: right;
}

::v-deep(.ant-select) {
  width: 492px !important;
}

::v-deep(.ant-modal-content .ant-modal-body) {
  padding: 0 24px 24px;
}

:deep(.ant-modal-wrap .msg-ant-modal .ant-modal-confirm-title) {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-modal-confirm-body .ant-modal-confirm-title) {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-modal-confirm .ant-modal-body) {
  padding: 2px 0 0 28px;
}

:deep(.ant-form-item-label > label::after) {
  margin: 0;
}

:deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 4px;
}

:deep(.ant-form-item .ant-input-textarea-show-count::after) {
  margin-bottom: 0;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
}

:deep(.ant-tabs-tab) {
  padding: 0 0 10px 0;
}

:deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  font-weight: 500;
  color: #000000;
}

:deep(.ant-tabs-content-holder) {
  margin-top: 16px;
}

:deep(.year .ant-form-item-label) {
  width: 52px;
}

:deep(.ant-form-item-label) {
  width: 112px;
}

.ant-table-wrapper {
  margin-top: 24px;
}

.ant-tabs-tabpane {
  display: flex;
  align-items: center;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 16px;
}

::v-deep(.ant-table-body) {
  // max-height: 460px !important;
}
</style>
<style lang="less">
.ant-tooltip {
  max-width: 700px;
}

.storageManage {
  .baseForm {
    .baseForm-sections {
      padding-bottom: 0px;
    }
  }
}
</style>
